package com.housekeeping.housekeeping.cleanerInformation.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author hua
 * @version JDK1.8
 * @date 2021/1/15 17:48
 */
public class DbManager {
    //定义加载配置文件的对象
    private static DataSource dataSource;
    private static final String PROPERTIES_NAME = "jdbc.properties";
    //静态代码块
    static {
        //声明一个连接对象
        Properties properties = new Properties();
        try {
            // 通过配置文件获取的
            properties.load(DbManager.class.getClassLoader().getResourceAsStream(PROPERTIES_NAME));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向外界提供一个数据库操作对象
     * @return
     */
    public static Connection getConnection() throws SQLException {
        //获取数据库连接对象
        Connection connection = dataSource.getConnection();
        //返回一个数据库连接对象
        return connection;
    }

    /**
     * 关流方法
     * @param resultSet 执行查询操作时返回的结果集
     * @param connection 数据库连接对象
     * @param statement 数据库连接流
     * @throws SQLException
     */
    public static void closeAll(ResultSet resultSet, Connection connection, Statement statement) throws SQLException {
        if (resultSet != null){
            resultSet.close();
        }
        if (connection != null){
            connection.close();
        }
        if (statement != null){
            statement.close();
        }
    }

    /**
     * 当执行的是 增删改 操作时不需要返回结果集
     * @param connection
     * @param statement
     * @throws SQLException
     */
    public static void closeAll(Connection connection, Statement statement) throws SQLException {
        closeAll(null,connection, statement);
    }
}
